package py.cursoweb.controller;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import py.cursoweb.model.Venta;

public class VentaManager {
private static ArrayList<Venta> ventas = null;
	
	public VentaManager() {
		if (ventas == null) {
			ventas = new ArrayList<Venta>();
		}
	}
	
	public List<Venta> getVentas() throws Exception {
		Session session = getSession();
		Transaction trans = session.beginTransaction();
		List<Venta> ventas;
		
		try {			
			ventas = session.createQuery("from Venta").list();
			trans.commit(); 
		}catch(Exception ex) {
			ex.printStackTrace();
			trans.rollback();
			
			throw ex;
		}			 
		
		return ventas;
	}
	
	public void addVenta(Venta venta) {
		ventas.add(venta);
	}
	
	public Venta getVenta(Integer id) {
		for(Venta venta : ventas) {
			if (venta.getId().equals(id))
				return venta;
		}
		
		return null;
	}
	
	
	//acceso a base de datos
	public void saveVenta(Venta venta) throws Exception {
		Session session = getSession();
		Transaction trans = session.beginTransaction();
		
		try {			
			session.saveOrUpdate(venta);
			trans.commit();
		}catch(Exception ex) {
			ex.printStackTrace();
			trans.rollback();
			
			throw ex;
		}			
	}
	
	public void deleteVenta(Venta venta) throws Exception {
		Session session = getSession();
		Transaction trans = session.beginTransaction();
		
		try {			
			session.delete(venta);
			trans.commit();
		}catch(Exception ex) {
			ex.printStackTrace();
			trans.rollback();
			
			throw ex;
		}			
	}
	
	public Session getSession() {
		return HibernateUtil.getSessionFactory().getCurrentSession();
	}
}
